package com.das.mechanic_base.widget;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.create.StaffSelectAdapter;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.base.X3IBaseView;
import com.das.mechanic_base.bean.create.SaveWorkSuccessBean;
import com.das.mechanic_base.bean.create.SelectWorkBean;
import com.das.mechanic_base.bean.create.ServiceInfoBean;
import com.das.mechanic_base.bean.create.StaffListBean;
import com.das.mechanic_base.bean.even.DeleteFriends;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.hjq.toast.ToastUtils;
import com.kproduce.roundcorners.RoundTextView;

import org.greenrobot.eventbus.EventBus;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class X3BottomStaffDialog extends X3BaseBottomSheetDialog implements View.OnClickListener, StaffSelectAdapter.IOnSelectStaff, X3MemberButtonView.IOnClickAffirm, X3BottomWorkTimeDialog.IOnSelectTime {

    private RoundTextView rv_now;
    private RoundTextView rv_ten_min;
    private RoundTextView rv_min;
    private RoundTextView rv_hour;
    private RoundTextView rv_self;
    private X3MemberButtonView btn_next;
    private RecyclerView rlv_staff;
    private LinearLayout ll_bottom;

    private TextView tv_time;
    private TextView tv_staff;


    /**
     * 0 立即开始
     * 1 10分钟后
     * 2 半小时后
     * 3 一小时后
     * 4 自定义
     */
    private int timeType = 0;

    private long selfTime = 0;
    private StaffSelectAdapter staffAdapter;
    private StaffListBean staffBean;

    private long receiveBaseId;
    private List<SelectWorkBean.ServiceBaseEntityBean> serviceBean;
    private ServiceInfoBean.WorkBaseBean workBaseBean;
    private X3BottomWorkTimeDialog timeDialog;
    private boolean isAssignStaff;
    private boolean isDetection;
    private boolean isReSet; // 重新检测

    public X3BottomStaffDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        rv_now = getView(R.id.rv_now);
        rv_ten_min = getView(R.id.rv_ten_min);
        rv_min = getView(R.id.rv_min);
        rv_hour = getView(R.id.rv_hour);
        rv_self = getView(R.id.rv_self);
        btn_next = getView(R.id.btn_next);
        rlv_staff = getView(R.id.rlv_staff);
        ll_bottom = getView(R.id.ll_bottom);
        tv_time = getView(R.id.tv_time);
        tv_staff = getView(R.id.tv_staff);

        rlv_staff.setLayoutManager(new LinearLayoutManager(mContext));
        staffAdapter = new StaffSelectAdapter(mContext);
        rlv_staff.setAdapter(staffAdapter);
        staffAdapter.setiOnSelectStaff(this);

        rv_now.setOnClickListener(this);
        rv_ten_min.setOnClickListener(this);
        rv_min.setOnClickListener(this);
        rv_hour.setOnClickListener(this);
        rv_self.setOnClickListener(this);

        btn_next.setiOnClickAffirm(this);

        labelColor(tv_time.getText().toString().trim(),tv_time);
        labelColor(tv_staff.getText().toString().trim(),tv_staff);

    }

    private void labelColor(String label, TextView tv){
        SpannableString contentSpan = new SpannableString(tv.getText().toString().trim());
        contentSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#313340")), 0, label.length()-1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        contentSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#F64444")), label.length()-1, label.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(contentSpan);
    }

    public void giveServiceVariantBean(long receiveBaseId,ServiceInfoBean.WorkBaseBean workBaseBean,boolean isDetection) {
        this.workBaseBean = workBaseBean;
        this.isDetection = isDetection;
        this.receiveBaseId = receiveBaseId;
        this.isAssignStaff = false;
    }

    public void giveServiceVariantBean(long receiveBaseId,ServiceInfoBean.WorkBaseBean workBaseBean,boolean isDetection,boolean isReSet) {
        this.workBaseBean = workBaseBean;
        this.isDetection = isDetection;
        this.receiveBaseId = receiveBaseId;
        this.isAssignStaff = false;
        this.isReSet = isReSet;
    }

    public void assignStaff(ServiceInfoBean.WorkBaseBean workBaseBean,boolean isDetection) {
        this.workBaseBean = workBaseBean;
        this.isAssignStaff = true;
        this.isDetection = isDetection;
        String startTime = workBaseBean.startTime;
        ll_bottom.setVisibility(View.GONE);
        if (X3StringUtils.isEmpty(startTime)) {
            return;
        }
        resetStaff();
        timeType = 4; // 由3修改为4 做新版本兼容
        changeRoundText(rv_now,false);
        changeRoundText(rv_self,true);
        rv_self.setText(X3DateUtils.SecondWithDay(startTime));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_bottom_staff_dialog;
    }

    @Override
    public void show() {
        super.show();
        ll_bottom.setVisibility(View.VISIBLE);
        btn_next.changeBtnStatus(false);
        resetStaff();
        requestStaff();
    }

    private void requestStaff() {
        NetWorkHttp.getApi().listStoreStaffBase()
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)mContext).bindToLife())
                .subscribe(new HttpCallBack<List<StaffListBean>>() {
                    @Override
                    protected void onDone(List<StaffListBean> staffListBeans) {
                        if (X3StringUtils.isListEmpty(staffListBeans)) {
                            staffListBeans = new ArrayList<>();
                        }
                        if (staffAdapter == null) {
                            return;

                        }
                        if (isAssignStaff) {
                            List<ServiceInfoBean.StaffBaseBean> staffBaseList = workBaseBean.staffBaseList;
                            staffAdapter.changeStaff(staffListBeans,X3StringUtils.isListEmpty(staffBaseList) ? 0 : staffBaseList.get(0).id);
                        }else {
                            staffAdapter.changeStaff(staffListBeans);
                        }
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    /**
     * 修改施工时间
     */
    private void updateWorkTime(Map<String,Object> map,List<Long> mList) {
        NetWorkHttp.getApi().updateWorkBaseTime(map,mList)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)mContext).bindToLife())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        DeleteFriends deleteFriends = new DeleteFriends("Create_Work_Order",isDetection);
                        EventBus.getDefault().post(deleteFriends);
                        if (iOnSaveWork != null) {
                            iOnSaveWork.iOnSaveWorkSuccess(null,isDetection);
                        }
                        if (timeType == 0) {
                            workBaseBean.status = 1;
                            dismiss();
                        }
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    private void resetStaff() {
        selfTime = 0;
        timeType = 0;
        changeRoundText(rv_now,true);
        changeRoundText(rv_min,false);
        changeRoundText(rv_hour,false);
        changeRoundText(rv_self,false);
        changeRoundText(rv_ten_min,false);
        rv_self.setText(mContext.getString(R.string.set_work_self_time));
    }

    private void changeRoundText(RoundTextView rv_view,boolean isSelect) {
        rv_view.setTypeface(isSelect ? Typeface.defaultFromStyle(Typeface.BOLD) : Typeface.defaultFromStyle(Typeface.NORMAL));
        rv_view.setStrokeColor(isSelect ? ContextCompat.getColor(mContext,R.color.bg_0077FF) : Color.TRANSPARENT);
        rv_view.setBackgroundColor(isSelect ? ContextCompat.getColor(mContext,R.color.c1A0077FF) : ContextCompat.getColor(mContext,R.color.white));
        rv_view.setTextColor(isSelect ? ContextCompat.getColor(mContext,R.color.bg_0077FF) : ContextCompat.getColor(mContext,R.color.c333));
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.rv_now) {
            if (workBaseBean != null && workBaseBean.status != 0) {
                ToastUtils.show(mContext.getString(R.string.x3_work_not_change_time));
                return;
            }
            resetStaff();
            clickAfter();

        } else if (view.getId() == R.id.rv_ten_min) {
            if (workBaseBean != null && workBaseBean.status != 0) {
                ToastUtils.show(mContext.getString(R.string.x3_work_not_change_time));
                return;
            }
            resetStaff();
            timeType = 1;
            changeRoundText(rv_now,false);
            changeRoundText(rv_min,false);
            changeRoundText(rv_ten_min,true);
            clickAfter();

        }else if (view.getId() == R.id.rv_min) {
            if (workBaseBean != null && workBaseBean.status != 0) {
                ToastUtils.show(mContext.getString(R.string.x3_work_not_change_time));
                return;
            }
            resetStaff();
            timeType = 2;
            changeRoundText(rv_now,false);
            changeRoundText(rv_ten_min,false);
            changeRoundText(rv_min,true);
            clickAfter();

        }else if (view.getId() == R.id.rv_hour) {
            if (workBaseBean != null && workBaseBean.status != 0) {
                ToastUtils.show(mContext.getString(R.string.x3_work_not_change_time));
                return;
            }
            resetStaff();
            timeType = 3;
            changeRoundText(rv_now,false);
            changeRoundText(rv_ten_min,false);
            changeRoundText(rv_hour,true);
            clickAfter();

        }else if (view.getId() == R.id.rv_self) {
            if (workBaseBean != null && workBaseBean.status != 0) {
                ToastUtils.show(mContext.getString(R.string.x3_work_not_change_time));
                return;
            }
            if (timeDialog == null) {
                timeDialog = new X3BottomWorkTimeDialog(mContext);
            }
            timeDialog.show();
            timeDialog.setiOnSelectTime(this);

        }
    }

    private void clickAfter() {
        if (workBaseBean != null && workBaseBean.status == 0) {
            startWork(workBaseBean);
        }
    }

    public void startStaffWork(long receiveBaseId, List<SelectWorkBean.ServiceBaseEntityBean> serviceBean,boolean isDetection) {
        this.receiveBaseId = receiveBaseId;
        this.serviceBean = serviceBean;
        this.isDetection = isDetection;
        this.isAssignStaff = false;
    }

    @Override
    public void iOnSelectStaff(StaffListBean staffListBean) {
        this.staffBean = staffListBean;
        btn_next.changeBtnStatus(true);
        if (!isAssignStaff) {
            return;
        }
        List<Long> staffList = new ArrayList<>();
        staffList.add(staffBean.id);

        NetWorkHttp.getApi().assignWorkStaff(workBaseBean.workBaseId,staffList)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)mContext).bindToLife())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        if (iOnSaveWork != null) {
                            iOnSaveWork.iOnRefreshData();
                        }
                        DeleteFriends deleteFriends = new DeleteFriends("Create_Work_Order",isDetection);
                        EventBus.getDefault().post(deleteFriends);
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }

    @Override
    public void iOnClickAffirm() {
        if (staffBean == null) {
            btn_next.reset();
            return;
        }
        List<String> idList = new ArrayList<>();
        idList.clear();
        if (workBaseBean != null) {
            if (isReSet){
                idList.add(workBaseBean.serviceBaseSn);
                NetWorkHttp.getApi().saveOrDeleteReceiveVariantForStandard(receiveBaseId,idList)
                        .compose(RxSchedulersHelper.defaultComposeRequest())
                        .compose(((X3IBaseView)mContext).bindToLife())
                        .subscribe(new HttpCallBack<ServiceInfoBean.WorkBaseBean>() {
                            @Override
                            protected void onDone(ServiceInfoBean.WorkBaseBean variantBean) {
                                workBaseBean.receiveVariantGroupNo = variantBean.receiveVariantGroupNo;
                                startWork(workBaseBean);
                            }

                            @Override
                            protected void showError(String error) {
                                btn_next.reset();
                            }
                        });
            } else {
                startWork(workBaseBean);
            }

            return;
        }
        if (X3StringUtils.isListEmpty(serviceBean)) {
            btn_next.reset();
            return;
        }

        for (int i = 0; i < serviceBean.size(); i++) {
            idList.add(serviceBean.get(i).sn);
        }

        NetWorkHttp.getApi().saveOrDeleteReceiveVariantForStandard(receiveBaseId,idList)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)mContext).bindToLife())
                .subscribe(new HttpCallBack<ServiceInfoBean.WorkBaseBean>() {
                    @Override
                    protected void onDone(ServiceInfoBean.WorkBaseBean variantBean) {
                        startWork(variantBean);
                    }

                    @Override
                    protected void showError(String error) {
                        btn_next.reset();
                    }
                });
    }

    private void startWork(ServiceInfoBean.WorkBaseBean variantBean) {
        if (variantBean == null) {
            return;
        }
        // TODO 目前只针对于立即开始
        long startTime = 0;
        String after;
        long afterTime = 0;
        switch (timeType) {
            case 0:
                startTime = System.currentTimeMillis();

                break;
            case 1:
                startTime = System.currentTimeMillis() + 1000 * 60 * 10;

                break;
            case 2:
                startTime = System.currentTimeMillis() + 1000 * 60 * 30;

                break;
            case 3:
                startTime = System.currentTimeMillis() + 1000 * 60 * 60;

                break;
            default:
                startTime = selfTime;

                break;
        }
        after = X3DateUtils.expriredDate(variantBean.occupyDuration * 60 * 100);
        afterTime = X3StringUtils.isEmpty(after) ? 0 : Long.parseLong(after);

        Map<String,Object> map = new HashMap<>();
        // 施工单开始时间时间戳
        map.put("startTimeTimestamp",startTime);
        map.put("deliveryTimeTimestamp",afterTime);
        map.put("deliveryDuration",variantBean.deliveryDuration);

        List<Long> mList = new ArrayList<>();
        mList.add(staffBean.id);

        if (isAssignStaff && variantBean.status == 0) {
            map.put("workBaseId",workBaseBean.workBaseId);
            updateWorkTime(map,mList);
            return;
        }else {
            map.put("receiveBaseId",receiveBaseId);
            map.put("groupNo",variantBean.receiveVariantGroupNo);
            if (isReSet){
                map.put("originalWorkBaseId",variantBean.workBaseId);
            }
        }

        NetWorkHttp.getApi().saveWorkBase(map,mList)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)mContext).bindToLife())
                .subscribe(new HttpCallBack<SaveWorkSuccessBean>() {
                    @Override
                    protected void onDone(SaveWorkSuccessBean successBean) {
                        btn_next.reset();
                        if (iOnSaveWork != null) {
                            iOnSaveWork.iOnSaveWorkSuccess(successBean,isDetection);
                        }
                        dismiss();
                    }

                    @Override
                    protected void NoNetCallBack() {
                        super.NoNetCallBack();
                        btn_next.reset();
                    }

                    @Override
                    protected void showError(String error) {
                        btn_next.reset();
                    }
                });
    }

    IOnSaveWorkBase iOnSaveWork;

    public X3BottomStaffDialog setiOnSaveWork(IOnSaveWorkBase iOnSaveWork) {
        this.iOnSaveWork = iOnSaveWork;
        return this;
    }

    @Override
    public void iOnSelectWorkTime(long longTime) {
        resetStaff();
        this.selfTime = longTime;
        rv_self.setText(X3DateUtils.longToStringForStaff(longTime));
        timeType = 3;
        changeRoundText(rv_now,false);
        changeRoundText(rv_self,true);
        clickAfter();
    }

    public interface IOnSaveWorkBase{
        /**
         * 安排施工成功 跳转到成功页面
         */
        void iOnSaveWorkSuccess(SaveWorkSuccessBean successBean,boolean isDetection);

        void iOnRefreshData();

    }
}
